package org.duomn.ichat.net.impl;

import java.io.IOException;
import java.net.SocketException;
import java.util.Map;

import org.duomn.ichat.entity.Message;
import org.duomn.ichat.entity.User;
import org.duomn.ichat.exception.MsgLoseException;
import org.duomn.ichat.gui.ChatFrame;
import org.duomn.ichat.gui.MainFrame;
import org.duomn.ichat.net.AbstractMsgHandler;
import org.duomn.ichat.thread.TCPThreadAbstract;
import org.duomn.ichat.thread.TCPThreadPASV;
import org.duomn.ichat.thread.TCPThreadPORT;
import org.duomn.ichat.util.Const;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ChatMsgHander extends AbstractMsgHandler {
	
	public ChatMsgHander(TCPThreadAbstract chatThread, Message message) {
		super(chatThread, message);
	}

	private static Logger logger = LoggerFactory.getLogger(ChatMsgHander.class);
	
	@Override
	public void handle()
			throws ClassNotFoundException, SocketException, IOException {
		Message msg = (Message) chatThread.getInputStream().readObject();
		handMsg(msg);
	}
	
	protected void handMsg(Message msg) {
		switch (msg.msgType) {
		case CLOSE_SESSION:
			chatThread.closeByReceive();
			break;
		case CHAT_INFO:
			handPASVChatMsg(msg);
			break;
		case LOGIN_IN:
			handPASVLoginMsg(msg);
			break;
		case LOGIN_OUT:
			handPASVLoginOutMsg(msg);
			break;
		default:
			logger.error("接受到了不能处理的消息，" + msg.data);
			break;
		}
	}

	/** 处理被动线程接受到的好友上线消息 */
	private void handPASVLoginMsg(Message msg) {
		Map<Integer, User> userMap = Const.get(Const.USER_MAP);
		int userId = msg.src;
		User user = (User) msg.data; 
		userMap.get(userId).setHost(user.getHost());
		userMap.get(userId).setPort(user.getPort());
		MainFrame.getInstance().updateData();
	}

	/** 处理被动线程接受到的好友下线消息 */
	private void handPASVLoginOutMsg(Message msg) {
		Map<Integer, User> userMap = Const.get(Const.USER_MAP);
		int userId = msg.src;
		userMap.get(userId).setPort(0);
		userMap.get(userId).setHost(null);
		MainFrame.getInstance().updateData();
	}

	/** 处理被动线程接受到的好友的消息 */
	private void handPASVChatMsg(Message msg) {
		if (chatThread instanceof TCPThreadPASV) { // 被动线程可能无窗口
			if (Const.<Integer>get(Const.USER_SELF_ID) == msg.src) { // 如果消息来源和当前用户相同，直接转发该消息
				try {
					chatThread.send(msg);
				} catch (MsgLoseException e) {
					logger.warn("与自己聊天转发异常", e);
				}
			} else { 
				if (chatThread.getUIHandler() != null) { // 已经有窗口
					chatThread.getUIHandler().handle(msg);
					return;
				} else { // 创建窗口，变建立关系
					User user = Const.<Map<Integer, User>>get(Const.USER_MAP).get(msg.src);
					if (user == null) {
						user = new User();
						user.setId(msg.src);
					}
					ChatFrame cf = ChatFrame.getInstance(user);
					chatThread.setUIHandler(cf);
					cf.setChatThread(chatThread);
					cf.handle(msg);
				}
			}
		} else if (chatThread instanceof TCPThreadPORT) { // 主动线程一定有窗口
			if (chatThread.getUIHandler() != null) {
				chatThread.getUIHandler().handle(msg);
			}
		}
	}
	
}
